package com.songlanyun.modules.schedule;

import com.songlanyun.common.annotation.SysLog;
import com.songlanyun.common.enums.OrderConstant;
import com.songlanyun.modules.marketing.groupbuy.entity.GroupBuyTeam;
import com.songlanyun.modules.marketing.groupbuy.service.GroupBuyTeamService;
import com.songlanyun.modules.order.entity.ChildOrder;
import com.songlanyun.modules.order.entity.Order;
import com.songlanyun.modules.order.service.ChildOrderService;
import com.songlanyun.modules.order.service.OrderOperationService;
import com.songlanyun.modules.order.service.OrderService;
import com.songlanyun.modules.payorder.entity.PayOrder;
import com.songlanyun.modules.payorder.service.PayOrderService;
import com.songlanyun.modules.refillorder.service.SaleRefillCardOrderService;
import com.songlanyun.modules.rights.entity.RightsOrder;
import com.songlanyun.modules.rights.service.RightsOrderService;
import com.songlanyun.modules.saleconfig.entity.SaleConfig;
import com.songlanyun.modules.saleconfig.service.SaleConfigService;
import com.songlanyun.modules.ship.entity.OrderPackage;
import com.songlanyun.modules.ship.service.OrderPackagePickupService;
import com.songlanyun.modules.ship.service.OrderPackageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 定时任务
 * <p>
 * 检测过期订单，修改状态
 */
@Component
@Configuration
@EnableScheduling
@Lazy(false)
@Slf4j
public class OrderScheduleServiceImpl {

    @Resource
    private PayOrderService payOrderService;

    @Resource
    private SaleRefillCardOrderService saleRefillCardOrderService;

    @Resource
    private OrderOperationService orderOperationService;

    @Resource
    private OrderService orderService;

    @Resource
    private ChildOrderService childOrderService;


    @Resource
    private OrderPackageService orderPackageService;

    @Resource
    private RightsOrderService rightsOrderService;

    @Resource
    private GroupBuyTeamService groupBuyTeamService;
    @Resource
    private SaleConfigService saleConfigService;
    /**
     * 订单支付过期按每分钟一次 已转移到MQ
     */

    @Scheduled(fixedDelay=60*1000)
    public void payExpireTask() {
        //获取过期订单
        List<PayOrder> list = payOrderService.getExpiredOrder(System.currentTimeMillis());
        list.forEach(v -> {
            try {
                log.info(String.format("支付订单:%s 过期，开始执行自动撤单", v.getCode()));
                if (v.getOrderType().equals(OrderConstant.OrderType.REFILL_ORDER)) {
                    //充值订单 关闭
                    saleRefillCardOrderService.closeOrder(v.getId());
                }
                if (v.getOrderType().equals(OrderConstant.OrderType.SALE_ORDER)) {
                    //消费订单
                    orderOperationService.payExpireCancel(v.getId());
                }
                log.info(String.format("支付订单:%s 过期，完成执行自动撤单", v.getCode()));
            }
            catch (Exception ex) {
                log.error(String.format("支付订单:%s 过期，执行自动撤单,出错%s", v.getCode(), ex.getMessage()));
            }

        });

    }

    /**
     * 普通消费自提订单,执行自动备货 已转移到MQ
     */
    // @Scheduled(fixedDelay=60*1000)
    public void autoStockUp() {
        List<Order> list = orderService.loadNeedAutoStockUp();
        list.forEach(v -> {

            try {
                log.info(String.format("普通消费自提订单:%s,开始执行自动备货", v.getOrderCode()));
                orderPackageService.autoPickupShip(v);
                log.info(String.format("普通消费自提订单:%s,完成执行自动备货", v.getOrderCode()));
            }
            catch (Exception ex) {
                log.error(String.format("普通消费自提订单:%s,执行自动备货,出错%s", v.getOrderCode(), ex.getMessage()));
            }
        });
    }

    /**
     * 普通消费物流订单,执行自动收货 已转移到MQ
     */
    // @Scheduled(fixedDelay=60*1000)
    public void autoShip() {
        List<OrderPackage> list = orderPackageService.needAutoReceipt();
        list.forEach(v -> {
            try {
                log.info(String.format("普通消费物流订单:%s,开始执行自动收货", v.getOrderCode()));
                orderPackageService.autoReceipt(v);
                log.info(String.format("普通消费物流订单:%s,完成执行自动收货", v.getOrderCode()));
            }
            catch (Exception ex) {
                log.error(String.format("普通消费物流订单:%s,执行自动收货,出错%s", v.getOrderCode(), ex.getMessage()));
            }
        });
    }

    /**
     * 普通自提订单,备货完成后，买家过期不来拿货，自动完成  已转移到MQ
     */

    //@Scheduled(cron = "${task0h5m}")
    public void autoPickup() {
        List<OrderPackage> list = orderPackageService.needAutoPickup();
        list.forEach(v -> {
            try {
                log.info(String.format("普通自提订单:%s,过期不来拿货，开始执行自动收货", v.getOrderCode()));
                orderPackageService.autoPickupReceipt(v);
                log.info(String.format("普通自提订单:%s,过期不来拿货，完成执行自动收货", v.getOrderCode()));
            }
            catch (Exception ex) {
                log.error(String.format("普通自提订单:%s,过期不来拿货，执行自动收货,出错%s", v.getOrderCode(), ex.getMessage()));
            }
        });
    }

    /**
     * 维权申请商家过期没处理自动同意
     */
    //@Scheduled(cron = "${task0h10m}")
    public void autoAgreeRights() {
        List<RightsOrder> list = rightsOrderService.needAutoAgree();
        list.forEach(v -> {
            try {
                log.info(String.format("维权订单:%s,维权申请商家过期没处理，开始执行货自动同意", v.getRightsCode()));
                rightsOrderService.autoAgree(v);
                log.info(String.format("维权订单:%s,维权申请商家过期没处理，完成执行货自动同意", v.getRightsCode()));
            }
            catch (Exception ex) {
                log.error(String.format("维权订单:%s,维权申请商家过期没处理，完成执行货自动同意,出错%s", v.getOrderCode(), ex.getMessage()));
            }
        });
    }

    /**
     * 商家同意之后，买家过期没有填写物流单，需要自动取消的维权单（退货单）
     */
    //@Scheduled(cron = "${task0h20m}")
    public void autoCancelRights() {
        List<RightsOrder> list = rightsOrderService.needAutoCancelRights();
        list.forEach(v -> {
            try {
                log.info(String.format("维权订单:%s,买家过期没有填写物流单，开始执行货自动取消", v.getRightsCode()));
                rightsOrderService.autoCancel(v);
                log.info(String.format("维权订单:%s,买家过期没有填写物流单，完成执行货自动取消", v.getRightsCode()));
            }
            catch (Exception ex) {
                log.error(String.format("维权订单:%s,买家过期没有填写物流单，完成执行货自动取消,出错%s", v.getOrderCode(), ex.getMessage()));
            }
        });
    }

    /**
     * 需要自动收货的维权单（退货单）
     */
    //@Scheduled(cron = "${task0h30m}")
    public void autoReceiptRights() {
        List<RightsOrder> list = rightsOrderService.needAutoReceiptRights();
        list.forEach(v -> {
            try {
                log.info(String.format("维权订单:%s,商家收货过期，开始执行货自动收货", v.getRightsCode()));
                rightsOrderService.autoReceipt(v);
                log.info(String.format("维权订单:%s,商家收货过期，完成执行货自动收货", v.getRightsCode()));
            }
            catch (Exception ex) {
                log.error(String.format("维权订单:%s,商家收货过期，完成执行货自动收货,出错%s", v.getOrderCode(), ex.getMessage()));
            }
        });
    }

    /**
     * 子订单封单 这个自动化必须要跑，因为维权可能让封单消息失效
     */
    @Scheduled(cron = "${task1h}")
    public void autoEnd() {
        List<ChildOrder> list = childOrderService.needAutoEndOrder();
        list.forEach(v -> {
            try {
                log.info(String.format("订单:%s,购买商品【%s】封单开始", v.getOrderCode(),v.getGoodsTitle()));
                childOrderService.endChildOrder(v);
                log.info(String.format("订单:%s,购买商品【%s】封单完成", v.getOrderCode(),v.getGoodsTitle()));
            }
            catch (Exception ex) {
                log.error(String.format("订单:%s,购买商品【%s】封单完成,出错%s", v.getOrderCode(),v.getGoodsTitle(), ex.getMessage()));
            }
        });
    }

    /**
     * 子订单自动评论
     */
    //@Async
    //@Scheduled(cron = "${task2h}")
    public void autoComment() {
        SaleConfig config = saleConfigService.getConfig();
        if(config!=null && config.getCommentOpen())
        {
            List<ChildOrder> list = childOrderService.needAutoCommentOrder();
            list.forEach(v -> {
                try {
                    log.info(String.format("订单:%s,购买商品【%s】自动评论开始", v.getOrderCode(),v.getGoodsTitle()));
                    childOrderService.autoCommentChildOrder(v);
                    log.info(String.format("订单:%s,购买商品【%s】自动评论完成", v.getOrderCode(),v.getGoodsTitle()));
                }
                catch (Exception ex) {
                    log.error(String.format("订单:%s,购买商品【%s】自动评论,出错%s", v.getOrderCode(),v.getGoodsTitle(), ex.getMessage()));
                }
            });
        }
    }


    /**
     * 过期没有成团的团需要取消
     */
    @Async
    @Scheduled(fixedDelay=120*1000)
    public void autoCancelTeam() {
        List<GroupBuyTeam> list = groupBuyTeamService.loadBuildExpire();
        list.forEach(v -> {
            try {
                log.info(String.format("编号:%s 过期没有组团成功，开始执行取消", v.getId().toString()));
                groupBuyTeamService.expireTeamHandle(v);
                log.info(String.format("编号:%s 过期没有组团成功，执行取消完成", v.getId().toString()));
            }
            catch (Exception ex) {
                log.error(String.format("编号:%s 过期没有组团成功，执行取消,出错%s", v.getId().toString(), ex.getMessage()));
            }
        });
    }

}